package com.ruoyi.web.controller.word;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.QiniuImageUploader;
import com.ruoyi.common.utils.youdao.FanyiV3Util;
import com.ruoyi.common.domain.word.CommonWord;
import com.ruoyi.common.domain.word.CommonWordForm;
import com.ruoyi.common.domain.word.CommonWordPronounce;
import com.ruoyi.word.service.ICommonWordFormService;
import com.ruoyi.word.service.ICommonWordPronounceService;
import com.ruoyi.word.service.ICommonWordService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/word/pronounce")
public class CommonWordPronounceController extends BaseController {

    public final Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ICommonWordPronounceService biz;

    @Autowired
    private ICommonWordService wordService;

    @Autowired
    private ICommonWordFormService formService;

    @RequestMapping(value = "/findByWid/{wid}", method = RequestMethod.GET)
    public R find(@PathVariable Long wid) {
        try{
            return R.data(biz.findByWid(wid));
        }catch(Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }


    // @Scheduled(fixedDelay = 1000*60*60*60)
    public R getPronounceFromYoudao(){
        try {
            List<CommonWord> wordList = wordService.findByWhereStr(null, "id", "desc");
            wordList.stream().forEach(word -> {
                try {
                    String result = FanyiV3Util.trans(word.getName());
                    // String result = "{\"returnPhrase\":[\"zoom\"],\"RequestId\":\"ef0e21a5-4d85-4947-8338-3ef24f5df945\",\"query\":\"zoom\",\"errorCode\":\"0\",\"l\":\"en2zh-CHS\",\"tSpeakUrl\":\"http://openapi.youdao.com/ttsapi?q=%E5%8F%98%E7%84%A6&langType=zh-CHS&sign=EAFC7F3C767E2DE5F3EE2F84E338F7D1&salt=1591088244204&voice=4&format=mp3&appKey=006f134b6f962944\",\"web\":[{\"value\":[\"缩放\",\"变焦\",\"超人集中营\",\"放大镜\"],\"key\":\"Zoom\"},{\"value\":[\"缩小\",\"缩小显示\",\"画面拉远\",\"放大\"],\"key\":\"zoom out\"},{\"value\":[\"变焦环\",\"变焦距圈\",\"变焦距环\"],\"key\":\"ZOOM RING\"}],\"translation\":[\"变焦\"],\"dict\":{\"url\":\"yddict://m.youdao.com/dict?le=eng&q=zoom\"},\"webdict\":{\"url\":\"http://m.youdao.com/dict?le=eng&q=zoom\"},\"basic\":{\"exam_type\":[\"高中\",\"GRE\",\"考研\"],\"us-phonetic\":\"zuːm\",\"phonetic\":\"zuːm\",\"uk-phonetic\":\"zuːm\",\"wfs\":[{\"wf\":{\"name\":\"复数\",\"value\":\"zooms\"}},{\"wf\":{\"name\":\"过去式\",\"value\":\"zoomed\"}},{\"wf\":{\"name\":\"过去分词\",\"value\":\"zooming\"}},{\"wf\":{\"name\":\"现在分词\",\"value\":\"zooming\"}},{\"wf\":{\"name\":\"第三人称单数\",\"value\":\"zooms\"}}],\"uk-speech\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=5&format=mp3&appKey=006f134b6f962944\",\"explains\":[\"v. （尤指汽车、飞机等）疾行；（价格、费用等）急剧增长，猛涨；（使镜头或摄影机）推近或拉远\",\"n. （车辆等）疾驰的声音，嗡嗡声；变焦摄影；急速上升\",\"int. （用于表示突然的快速移动）嗖地\"],\"us-speech\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=6&format=mp3&appKey=006f134b6f962944\"},\"isWord\":true,\"speakUrl\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=4&format=mp3&appKey=006f134b6f962944\"}";
                    System.out.println(result);
                    JSONObject jo = JSON.parseObject(result);
                    if(jo == null || jo.getJSONObject("basic") == null) {
                        System.out.println("word err: " + word.getName());
                    }
                    JSONObject basic = jo.getJSONObject("basic");
                    CommonWordPronounce pronounce = new CommonWordPronounce();
                    pronounce.setAddTime(new Date());
                    pronounce.setWid(word.getId());
                    pronounce.setType(1);
                    pronounce.setContent(basic.getString("uk-phonetic"));
                    pronounce.setAudio(uploadToQiniu(basic.getString("uk-speech"), word.getName(), "1"));

                    CommonWordPronounce pronounce2 = new CommonWordPronounce();
                    pronounce2.setAddTime(new Date());
                    pronounce2.setWid(word.getId());
                    pronounce2.setType(2);
                    pronounce2.setContent(basic.getString("us-phonetic"));
                    pronounce2.setAudio(uploadToQiniu(basic.getString("us-speech"), word.getName(), "2"));
                    System.out.println(JSON.toJSONString(pronounce));
                    System.out.println(JSON.toJSONString(pronounce2));
                    biz.saveByWord(word, new ArrayList(){{add(pronounce);add(pronounce2);}});

                    // 获取单词其他形式
                    JSONArray ja = basic.getJSONArray("wfs");
                    if(ja != null) {
                        List<CommonWordForm> list = new ArrayList<>();
                        for (Object wf: ja) {
                            JSONObject wfo = ((JSONObject)wf).getJSONObject("wf");
                            CommonWordForm form = new CommonWordForm();
                            form.setAddTime(new Date());
                            form.setWid(word.getId());
                            form.setWord(word.getName());
                            form.setName(wfo.getString("name"));
                            form.setValue(wfo.getString("value"));
                            list.add(form);
                        }
                        formService.saveByWord(word, list);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

//    @Scheduled(fixedDelay = 1000*60*60*60)
//    public R getPronounceFromYoudao(){
//        try {
//            List<CommonWord> wordList = wordService.findByWhereStr(null, "id", "desc");
//            wordList.stream().forEach(word -> {
//                try {
////                    String result = FanyiV3Util.trans(word.getName());
//                    String result = "{\"returnPhrase\":[\"zoom\"],\"RequestId\":\"ef0e21a5-4d85-4947-8338-3ef24f5df945\",\"query\":\"zoom\",\"errorCode\":\"0\",\"l\":\"en2zh-CHS\",\"tSpeakUrl\":\"http://openapi.youdao.com/ttsapi?q=%E5%8F%98%E7%84%A6&langType=zh-CHS&sign=EAFC7F3C767E2DE5F3EE2F84E338F7D1&salt=1591088244204&voice=4&format=mp3&appKey=006f134b6f962944\",\"web\":[{\"value\":[\"缩放\",\"变焦\",\"超人集中营\",\"放大镜\"],\"key\":\"Zoom\"},{\"value\":[\"缩小\",\"缩小显示\",\"画面拉远\",\"放大\"],\"key\":\"zoom out\"},{\"value\":[\"变焦环\",\"变焦距圈\",\"变焦距环\"],\"key\":\"ZOOM RING\"}],\"translation\":[\"变焦\"],\"dict\":{\"url\":\"yddict://m.youdao.com/dict?le=eng&q=zoom\"},\"webdict\":{\"url\":\"http://m.youdao.com/dict?le=eng&q=zoom\"},\"basic\":{\"exam_type\":[\"高中\",\"GRE\",\"考研\"],\"us-phonetic\":\"zuːm\",\"phonetic\":\"zuːm\",\"uk-phonetic\":\"zuːm\",\"wfs\":[{\"wf\":{\"name\":\"复数\",\"value\":\"zooms\"}},{\"wf\":{\"name\":\"过去式\",\"value\":\"zoomed\"}},{\"wf\":{\"name\":\"过去分词\",\"value\":\"zooming\"}},{\"wf\":{\"name\":\"现在分词\",\"value\":\"zooming\"}},{\"wf\":{\"name\":\"第三人称单数\",\"value\":\"zooms\"}}],\"uk-speech\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=5&format=mp3&appKey=006f134b6f962944\",\"explains\":[\"v. （尤指汽车、飞机等）疾行；（价格、费用等）急剧增长，猛涨；（使镜头或摄影机）推近或拉远\",\"n. （车辆等）疾驰的声音，嗡嗡声；变焦摄影；急速上升\",\"int. （用于表示突然的快速移动）嗖地\"],\"us-speech\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=6&format=mp3&appKey=006f134b6f962944\"},\"isWord\":true,\"speakUrl\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=4&format=mp3&appKey=006f134b6f962944\"}";
//                    System.out.println(result);
//                    JSONObject jo = JSON.parseObject(result);
//                    if(jo == null || jo.getJSONObject("basic") == null) {
//                        System.out.println("word err: " + word.getName());
//                    }
//                    JSONObject basic = jo.getJSONObject("basic");
//                    CommonWordPronounce pronounce = new CommonWordPronounce();
//                    pronounce.setAddTime(new Date());
//                    pronounce.setWid(word.getId());
//                    pronounce.setType(1);
//                    pronounce.setContent(basic.getString("uk-phonetic"));
//                    pronounce.setAudio(uploadToQiniu(basic.getString("uk-speech"), word.getName(), "1"));
//
//                    CommonWordPronounce pronounce2 = new CommonWordPronounce();
//                    pronounce2.setAddTime(new Date());
//                    pronounce2.setWid(word.getId());
//                    pronounce2.setType(2);
//                    pronounce2.setContent(basic.getString("us-phonetic"));
//                    pronounce2.setAudio(uploadToQiniu(basic.getString("us-speech"), word.getName(), "2"));
//                    System.out.println(JSON.toJSONString(pronounce));
//                    System.out.println(JSON.toJSONString(pronounce2));
//                    biz.saveByWord(word, new ArrayList(){{add(pronounce);add(pronounce2);}});
//
//                    // 获取单词其他形式
//                    JSONArray ja = basic.getJSONArray("wfs");
//                    if(ja != null) {
//                        List<CommonWordForm> list = new ArrayList<>();
//                        for (Object wf: ja) {
//                            JSONObject wfo = ((JSONObject)wf).getJSONObject("wf");
//                            CommonWordForm form = new CommonWordForm();
//                            form.setAddTime(new Date());
//                            form.setWid(word.getId());
//                            form.setWord(word.getName());
//                            form.setName(wfo.getString("name"));
//                            form.setValue(wfo.getString("value"));
//                            list.add(form);
//                        }
//                        formService.saveByWord(word, list);
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//            });
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return R.error();
//    }

    @Scheduled(fixedDelay = 1000*60*60)
    public void updateSomePronounce() {
        List<CommonWord> wordList = wordService.findByWrongPronounce();
        wordList.forEach(w -> {
            try {
                saveOrUpdatePronounce(w);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    public void saveOrUpdatePronounce(CommonWord word) throws IOException {
//        String result = FanyiV3Util.trans(word.getName());
//        // String result = "{\"returnPhrase\":[\"zoom\"],\"RequestId\":\"ef0e21a5-4d85-4947-8338-3ef24f5df945\",\"query\":\"zoom\",\"errorCode\":\"0\",\"l\":\"en2zh-CHS\",\"tSpeakUrl\":\"http://openapi.youdao.com/ttsapi?q=%E5%8F%98%E7%84%A6&langType=zh-CHS&sign=EAFC7F3C767E2DE5F3EE2F84E338F7D1&salt=1591088244204&voice=4&format=mp3&appKey=006f134b6f962944\",\"web\":[{\"value\":[\"缩放\",\"变焦\",\"超人集中营\",\"放大镜\"],\"key\":\"Zoom\"},{\"value\":[\"缩小\",\"缩小显示\",\"画面拉远\",\"放大\"],\"key\":\"zoom out\"},{\"value\":[\"变焦环\",\"变焦距圈\",\"变焦距环\"],\"key\":\"ZOOM RING\"}],\"translation\":[\"变焦\"],\"dict\":{\"url\":\"yddict://m.youdao.com/dict?le=eng&q=zoom\"},\"webdict\":{\"url\":\"http://m.youdao.com/dict?le=eng&q=zoom\"},\"basic\":{\"exam_type\":[\"高中\",\"GRE\",\"考研\"],\"us-phonetic\":\"zuːm\",\"phonetic\":\"zuːm\",\"uk-phonetic\":\"zuːm\",\"wfs\":[{\"wf\":{\"name\":\"复数\",\"value\":\"zooms\"}},{\"wf\":{\"name\":\"过去式\",\"value\":\"zoomed\"}},{\"wf\":{\"name\":\"过去分词\",\"value\":\"zooming\"}},{\"wf\":{\"name\":\"现在分词\",\"value\":\"zooming\"}},{\"wf\":{\"name\":\"第三人称单数\",\"value\":\"zooms\"}}],\"uk-speech\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=5&format=mp3&appKey=006f134b6f962944\",\"explains\":[\"v. （尤指汽车、飞机等）疾行；（价格、费用等）急剧增长，猛涨；（使镜头或摄影机）推近或拉远\",\"n. （车辆等）疾驰的声音，嗡嗡声；变焦摄影；急速上升\",\"int. （用于表示突然的快速移动）嗖地\"],\"us-speech\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=6&format=mp3&appKey=006f134b6f962944\"},\"isWord\":true,\"speakUrl\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=4&format=mp3&appKey=006f134b6f962944\"}";
//        System.out.println(result);
//        JSONObject jo = JSON.parseObject(result);
//        if(jo == null || jo.getJSONObject("basic") == null) {
//            System.out.println("word err: " + word.getName());
//            return;
//        }
//        // 删除旧记录
//        biz.deleteByWid(word.getId());
//        // 创建新记录
//        JSONObject basic = jo.getJSONObject("basic");
//        CommonWordPronounce pronounce = new CommonWordPronounce();
//        pronounce.setAddTime(new Date());
//        pronounce.setWid(word.getId());
//        pronounce.setType(1);
//        pronounce.setContent(basic.getString("uk-phonetic"));
//        pronounce.setAudio(uploadToQiniu(basic.getString("uk-speech"), word.getName(), "1"));
//
//        CommonWordPronounce pronounce2 = new CommonWordPronounce();
//        pronounce2.setAddTime(new Date());
//        pronounce2.setWid(word.getId());
//        pronounce2.setType(2);
//        pronounce2.setContent(basic.getString("us-phonetic"));
//        pronounce2.setAudio(uploadToQiniu(basic.getString("us-speech"), word.getName(), "2"));
//        System.out.println(JSON.toJSONString(pronounce));
//        System.out.println(JSON.toJSONString(pronounce2));
//        biz.saveByWord(word, new ArrayList(){
//            private static final long serialVersionUID = -1L;
//            {add(pronounce); add(pronounce2);}
//        });
        List<CommonWordPronounce> pronounceList = biz.findByWid(word.getId());
        if(CollectionUtils.isEmpty(pronounceList)) {
            return;
        }
        pronounceList.forEach(d -> {
            try {
                if(StringUtils.contains(d.getAudio(), "token=")) {
                    d.setAudio(uploadToQiniu(null, word.getName(), d.getType().toString()));
                    biz.updateByPrimaryKeySelective(d);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private static String uploadToQiniu(String url, String word, String type) throws IOException {
        url = "https://dict.youdao.com/dictvoice?audio=" + word + "&type=" + type;
        String fileName = "xbky/dms/pronounce/" + type + "/" + word;

//        MyRet ret = QiniuImageUploader.upload(FanyiV3Util.getByteFromUrl(url), fileName, "bukaa-common");
//        System.out.println(ret.url.replaceAll("%2F", "/"));
//        return ret.url.replaceAll("%2F", "/");

        try {
            QiniuImageUploader.MyRet ret = QiniuImageUploader.upload(FanyiV3Util.getByteFromUrl(url), fileName, "bukaa-common");
            System.out.println(ret.url.replaceAll("%2F", "/"));
            return ret.url.replaceAll("%2F", "/");
        }catch (Exception e){
            return "http://cdn.ikaoyaner.com/xbky/dms/pronounce/"+ type + "/"+word;
        }
    }

    /**
     * 全量补偿单次发音缺失的单次
     * @return
     */
    @RequestMapping(value = "/compensation/all", method = RequestMethod.GET)
    public void compensation() {
        biz.compensationAll();
    }

    @RequestMapping(value = "/save/content", method = RequestMethod.GET)
    public void saveContentIsNull() {
        biz.contentIsNullSave();
    }

}
